package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFormFilter extends FormAuthenticationFilter{
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        // 开发中 用于 测试数据
        e.printStackTrace(System.out);
        // 设置 信息
        String msg = "网络错误";
        if (e instanceof UnknownAccountException) {
            msg = "用户名不存在";
        } else if (e instanceof IncorrectCredentialsException) {
            msg = "密码错误";
        }
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(new JsonResult().mark(msg)));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(new JsonResult()));
        return false;
    }

    // 可以 重复登录的 方法

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 是否是 登录请求
        if (isLoginRequest(request, response)) {
            // 登录的话 就 注销
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                return false;
//                subject.logout();
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
